//
//  AppManager.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/10/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "AppManager.h"
#import "DataManager.h"

#import "Reachability.h"

#import "WebServiceManager.h"
#import "DataManager.h"
#import "WaitTooles.h"

#import "PMGlobal.h"

#import "config.h"

#import "JSONKit.h"
#import "TipView.h"

#import "RFService.h"
#import "RFResponse.h"
//十分钟
#define DEFAULT_UPDATE_INTERVAL (60*30)

#define DEFAULT_TIPUPDATE_INTERVAL (5*60)
//十分钟
#define DEFAULT_SUBMIT_INTERVAL (10*60)

static AppManager *_sharedManager = nil;

@interface AppManager(){
    
    
    double updateInterval_;//单位为秒
    double tipupdateInterval_;
    double submitInterval_;//单位为秒
    
    double updateTick_;
    double submitTick_;
    
    int orderIndex_;
    
    BOOL update_flag_;
    BOOL submit_flag_;
    
    BOOL isSubmitting_;
    
    UIAlertView *loadingAlert_;
    BOOL isshowalert;
}

@property (atomic, assign) BOOL isSubmitting_;

@end

@implementation AppManager
@synthesize isSubmitting_;

+ (AppManager *)sharedManager {
    @synchronized( [AppManager class] ){
        if(!_sharedManager)
            _sharedManager = [[self alloc] init];
        return _sharedManager;
    }
    return nil;
}

+ (id)alloc {
    @synchronized ([AppManager class]){
        NSAssert(_sharedManager == nil,
                 @"Attempted to allocated a second instance");
        _sharedManager = [super alloc];
        return _sharedManager;
    }
    return nil;
}

- (id)init {
    self = [super init];
    if (self) {
        submit_flag_ = NO;
        update_flag_ = NO;
        isSubmitting_ = NO;
        isshowalert = NO;
        [self loadIntervalValue];
        
        [self createUpdateSession];
        [self createSubmitSession];
        
        [self pauseAutoSubmitSession];
        [self pauseAutoUpdateSession];
        
    }
    return self;
}

- (NSString *)getDatabasePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    NSString *filename = [NSString stringWithFormat:@"TUMeeting_%@.db",CUSTOMER_NAME];
    NSString *path = [cacheDir stringByAppendingPathComponent:filename];
    return path;
}

- (NSString *)getImagePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    return cacheDir;
}

- (NSString *)getBundleDatabasePath{
    NSString *filename = [NSString stringWithFormat:@"TUMeeting_%@.db",CUSTOMER_NAME];
    NSString *path = [[NSBundle mainBundle] bundlePath];
    path = [path stringByAppendingPathComponent:CUSTOMER_PATH];
    return [path stringByAppendingPathComponent:filename];
}

- (NSString *)getImageFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    cacheDir = [cacheDir stringByAppendingPathComponent:@"image"];
    NSError *err = nil;
    BOOL dir = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDir isDirectory:&dir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:&err];
    }
    return cacheDir;
}

- (void)loadIntervalValue{
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    
    NSString *val = [defs objectForKey:@"pm_update_interval"];
    if (val) {
        updateInterval_ = [val doubleValue];
    }else{
        updateInterval_ = DEFAULT_UPDATE_INTERVAL;
        tipupdateInterval_ = DEFAULT_TIPUPDATE_INTERVAL;
    }
    
    val = [defs objectForKey:@"pm_submit_interval"];
    if (val) {
        submitInterval_ = [val doubleValue];
    }else{
        submitInterval_ = DEFAULT_SUBMIT_INTERVAL;
    }
}


- (void)setUpdateInterval:(float)seconds{
    if (updateInterval_<0) {
        updateInterval_ = DEFAULT_UPDATE_INTERVAL;
    }else{
        updateInterval_ = seconds;
    }
}

- (BOOL)getSubmitStatus{
    return isSubmitting_;
}

- (void)setSubmitInterval:(float)seconds{
    if (submitInterval_<0) {
        submitInterval_ = DEFAULT_SUBMIT_INTERVAL;
    }else{
        submitInterval_ = seconds;
    }
    
}

- (void)setOrderIndex:(int)index{
    orderIndex_= index;
}

- (void)setSubmitStatus:(BOOL)status{
     isSubmitting_ = status;
}

- (void)forceUpdate:(DMCompletion)completion{
    [[DataManager sharedManager] forceUpdate:^(id res){
        completion(nil);
    }];
}

- (void)updateDatabase{
    if (![[DataManager sharedManager] hasUpdate]) {
        [[DataManager sharedManager] updateProductTable:nil];
        [[DataManager sharedManager] updateProductColoridTable:nil];
        [[DataManager sharedManager] updateProductPictureTable:nil];
//        [[DataManager sharedManager] updateSpdmStatusTimeTable:nil];
        [[DataManager sharedManager] updateSuitPm:nil];
//        [[DataManager sharedManager] updateOrder:nil];
        [[DataManager sharedManager] updateg_Size:nil];
        
       // [[DataManager sharedManager] updateSpdmSize:nil];
    }
    /*
    if (![[DataManager sharedManager]hasTipUpdate]) {
        [[DataManager sharedManager] performSelectorOnMainThread:@selector(updateTip:) withObject:nil waitUntilDone:YES];
    }
    */
    if ([[DataManager sharedManager] hasUpdate]) {
        if (isshowalert==NO) {
            [self performSelectorOnMainThread:@selector(showAlert) withObject:nil waitUntilDone:YES];
        }
    }
    /*
    if ([[DataManager sharedManager]hasTipUpdate]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"showtip" object:nil];
       // [[DataManager sharedManager]showtip];
        [[DataManager sharedManager]performTipUpdate];
    }
     */
}

- (void)updateTipDatabase{
    if (![[DataManager sharedManager]hasTipUpdate]) {
        [[DataManager sharedManager] performSelectorOnMainThread:@selector(updateTip:) withObject:nil waitUntilDone:YES];
    }
    if ([[DataManager sharedManager]hasTipUpdate]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"showtip" object:nil];
       // [[DataManager sharedManager]showtip];
        [[DataManager sharedManager]performTipUpdate];
    }
}


- (void)showAlert{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"基础资料更新"
                                                    message:@"是否进行更新?"
                                                   delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
    [alert show];
    isshowalert = YES;
}


- (void)update{
    [WaitTooles showHUD:@"正在更新中..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [[DataManager sharedManager] performSelectorInBackground:@selector(performUpdate) withObject:nil];
    });

   // [self performSelectorOnMainThread:@selector(removeLoadView) withObject:nil waitUntilDone:YES];
}
/*
- (void)removeLoadView{
    [loadingAlert_ dismissWithClickedButtonIndex:0 animated:YES];
    loadingAlert_ = nil;
}
*/
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (loadingAlert_!=alertView) {
        if (buttonIndex==1) {
            //[self performSelectorOnMainThread:@selector(showHUD) withObject:nil waitUntilDone:YES];
            //[self performSelectorOnMainThread:@selector(update) withObject:nil waitUntilDone:YES];
            [self performSelector:@selector(update) withObject:nil afterDelay:1.0];
        }
    }
    isshowalert = NO;
}


- (void)submitByShopID:(NSString *)shopid completion:(DMCompletion)completion{
    __block ShopObject *shopobj = [[DataManager sharedManager]getShopObjectByID:shopid];
    __block NSArray *array = [[DataManager sharedManager] getOrderInfo:shopobj.shopID Submit:0];
    //    __block int index = 0;
    
    
    if (array.count==0) {
        completion(nil);
        return;
    }
    
    __block OrderObject *obj = [array objectAtIndex:orderIndex_];
    //orderIndex_++;
    [self submitOneOrder:obj completion:^(NSDictionary *flag){
        
        if ([flag objectForKey:@"Table"]) {
            NSDictionary *dic = [[flag objectForKey:@"Table"]objectAtIndex:0];
            int ioresult = [[dic objectForKey:@"ioresult"] intValue];
            if (ioresult==1) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"订单提交" message:[dic objectForKey:@"Result"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                completion(nil);
                return;
            }
            [[DataManager sharedManager] markOrderAsUploaded:obj time:[dic objectForKey:@"MaxDatetime"] shop:shopobj];
            //if (orderIndex_<array.count-1) {
            [self submit:completion];
            //}else{
            //    completion(nil);
            //}
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh1" object:nil];
        }else{
            completion(nil);
        }
    }];
}

- (void)submit:(DMCompletion)completion{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    [self submitByShopID:shopobj.shopID completion:completion];
}

- (void)submitOrder{
    
    if ([[DataManager sharedManager]getUserObject]==nil) {
        return;
    }
    /*
    if (self.isSubmitting_) {
        return;
    }
    */
    orderIndex_ = 0;
    self.isSubmitting_ = YES;
    
    ShopObject *shopobj=[[DataManager sharedManager]getCurrentShop];
    if ([[DataManager sharedManager] getOrderedProducts:nil Shopid:shopobj.shopID Submit:0].count>0) {
        [self forceSubmitAllOrder:^(id res){
            
        }];
    }
    

    
//    [self submit:^(id res){
//        self.isSubmitting_ = NO;
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"refreshstatistic" object:nil];
//    }];
}

- (void)stopAutoUpdate{
    NSLog(@"更新进程停止");
    update_flag_ = NO;
    updateTick_ = updateInterval_;
}

- (void)startAutoUpdateSession{
    NSLog(@"更新进程开始");
    update_flag_ = YES;
    updateTick_ = 10;
}

- (void)pauseAutoUpdateSession{
    NSLog(@"更新进程暂停");
    update_flag_ = NO;
}

- (void)resumeAutoUpdateSession{
    NSLog(@"更新进程恢复");    
    update_flag_ = YES;
}

- (void)stopAutoSubmit{
    submit_flag_ = NO;
    submitTick_ = submitInterval_;
}

- (void)startAutoSubmitSession{
    submit_flag_ = YES;
    submitTick_ = 10;
}

- (void)resumeAutoSubmitSession{
    submit_flag_ = YES;
}

- (void)pauseAutoSubmitSession{
    submit_flag_ = NO;
}

- (void)resetAutoSubmitSession{
    submit_flag_ = YES;
    submitTick_ = submitInterval_;
    [self resumeAutoSubmitSession];
}

- (void)resetAutoUpdateSession{
    update_flag_ = YES;
    updateTick_ = updateInterval_;
    [self resumeAutoUpdateSession];
}

- (void)createSubmitSession{
    
    dispatch_queue_t submit_queue = dispatch_queue_create("com.yx.pm.submit", NULL);
    dispatch_async(submit_queue, ^(void) {
        
        sleep(5+arc4random()%10);
        
        NSLog(@"开始自动提交线程");
        while (1) {
            
            if (submit_flag_ && submitTick_<=0) {
                NSLog(@"后台自动提交订单");
                
#ifdef ENABLE_LAN_CHECK
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[PMGlobal getInstance] isWifiOn:^(id res){
                        if (res!=nil) {
                            [[PMGlobal getInstance] setNetworkFlag:1];
                        }else{
                            [[PMGlobal getInstance] setNetworkFlag:0];
                        }
                    }];
                });
#endif
                
                [self performSelectorOnMainThread:@selector(submitOrder) withObject:nil waitUntilDone:YES];
                submitTick_ = submitInterval_;
            }
            
            sleep(10);
            submitTick_-=10;

            
        }
        
        NSLog(@"自动提交线程终止");
    });
}

- (void)createUpdateSession{
    dispatch_queue_t update_queue = dispatch_queue_create("com.yx.pm.update", NULL);
    dispatch_async(update_queue, ^(void) {
        
        sleep(5+arc4random()%10);
        
        NSLog(@"开始自动更新线程");
        while (1) {
            
            if (update_flag_ && updateTick_<=0) {
                if ([[DataManager sharedManager] getUserObject]) {
                    NSLog(@"后台自动更新资料");
                    dispatch_async(dispatch_get_main_queue(), ^{
                    
                        [self updateDatabase];
                        [self updateTipDatabase];
                    
                        updateTick_ = updateInterval_;
                    });
                }
                               
            }
            sleep(10);
            updateTick_-=10;
        }
        
        NSLog(@"自动更新线程终止");
    });

}

- (void)submitOrders:(WebServiceCompletion)completion{

    NSMutableArray* arr = [[DataManager sharedManager] getOrderInfo:nil Submit:0];
    
    if (arr.count==0) {
        completion(nil);
        return;
    }

    for (OrderObject* order in arr) {
        [self submitOneOrder:order completion:^(NSDictionary *response){
            
            if (![response isKindOfClass:[NSDictionary class]]) {
                completion(nil);
            }else{
                completion(response);
            }
            
        }];
    }
    
}


- (void)forceSubmitOrder:(DMCompletion)completion{
    [[DataManager sharedManager] forceSubmit:completion];
}

- (void)forceSubmitAllOrder:(DMCompletion)completion{
    [[DataManager sharedManager] clearOrderUptime];
    [[DataManager sharedManager] forceSubmitAllOrder:completion];
}


- (void)submitOneOrder:(OrderObject*)order completion:(WebServiceCompletion)completion  {

    NSMutableArray *res = [NSMutableArray array];
        
        NSDictionary *quantity = order.quantity;
        for (NSString *key in quantity) {
            NSMutableDictionary *orderDic = [NSMutableDictionary dictionary];
            
            NSArray *shopAndSize = [key componentsSeparatedByString:@"_"];
            
            int sizeNo = [[shopAndSize objectAtIndex:0] intValue];
            NSString *shopid = [shopAndSize objectAtIndex:1];
            int number = [[quantity objectForKey:key] intValue];
            NSString *pCode = order.pCode;
            NSString *pColor = [NSString stringWithFormat:@"%@", order.pColorCode];
            
            ProductObject *obj = [[DataManager sharedManager] getProduct:pCode withColorID:pColor];
            
            NSString *userCode = [[DataManager sharedManager] getUserObject].userCode;
            
            [orderDic setObject:[NSNumber numberWithInt:sizeNo] forKey:@"xsize"];
            [orderDic setObject:shopid forKey:@"shopid"];
            [orderDic setObject:pCode forKey:@"code"];
            [orderDic setObject:pColor forKey:@"colorid"];
            [orderDic setObject:[NSNumber numberWithInt:number] forKey:@"amount"];
            [orderDic setObject:userCode forKey:@"usercode"];
            [orderDic setObject:[NSNumber numberWithFloat:obj.pSale*number] forKey:@"sale"];
//            [orderDic setObject:[NSNumber numberWithFloat:obj.pRatio] forKey:@"rebate"];
            [orderDic setObject:[NSNumber numberWithInt:obj.pSale] forKey:@"orgprice"];
            [orderDic setObject:[NSNumber numberWithInt:obj.pSale] forKey:@"price"];
            
            [orderDic setObject:@"0" forKey:@"scripno"];
            
            [res addObject:orderDic];
        }
    
    NSString *json = [res JSONString];
    [[WebServiceManager sharedManager] submit:json completion:^(NSDictionary *response){
        
        completion(response);
    }];
}

@end
